package com.shoppingmall.photowall;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import com.example.shoppingmall.R;
import com.shopping.tools.CategoryListTools;
import com.shopping.tools.Constant;
import com.shopping.tools.GetUrlMethod;
import com.shopping.tools.PullToRefreshBase.OnRefreshListener;
import com.shopping.tools.PullToRefreshGridView;
import com.shoppingmall.Adapter.PhotoWallAdapter;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * 照片墙分类解析
 * 
 */
public class PhotoWallAnalyze extends Fragment {
	private PhotoWallAdapter mPhotoWallAdapter;
	private ProgressDialog progress;
	private int pager = -1;
	private PullToRefreshGridView mPullRefreshGridView;
	private GridView gridview;
	private GridThread gridthread;
	private String req, queryDate;
	private View view;
	private ArrayList<HashMap<String, String>> listData = new ArrayList<HashMap<String, String>>();

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.photowall_gridview, container, false);
		progress = ProgressDialog.show(getActivity(), "", "正在加载。。。。", true,
				true);// 设置加载的ProgressDialog
		mPullRefreshGridView = (PullToRefreshGridView) view
				.findViewById(R.id.gridview_photowall);
		gridview = mPullRefreshGridView.getRefreshableView();
		queryDate = Constant.queryDate;
		mPhotoWallAdapter = new PhotoWallAdapter(getActivity(), listData);
		gridview.setAdapter(mPhotoWallAdapter);
		gridthread = new GridThread();
		gridthread.start();
		show();
		//下拉刷新
		mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// Do work to refresh the list here.
				new GetDataTask().execute();
			}

			@Override
			public void onLoading() {
			}
		});

		return view;
	}

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {

		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
			return null;
		}

		@Override
		protected void onPostExecute(String[] result) {
			mPhotoWallAdapter.notifyDataSetChanged();
			mPullRefreshGridView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	// 分页加载
	private void show() {
		// TODO Auto-generated method stub
		gridview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					if ((gridthread == null || !gridthread.isAlive())
							&& ((Integer.valueOf(Constant.pager) > pager))) {
						gridthread = new GridThread();
						gridthread.start();
					}

				}

			}
		});
	}

	// 线程
	private class GridThread extends Thread {
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			pager++;
			req = "{\"mallId\":1,\"queryDate\":\"" + queryDate + "\",\"page\":"
					+ pager + ",\"limit\":9}";// 照片墙参数
			String urlPath;
			try {
				urlPath = GetUrlMethod.getURLString(Constant.photoWallurl
						+ URLEncoder.encode(req, "utf-8"));
				CategoryListTools.json_PhotoWall(urlPath, listData);// 对数据进行解析
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Message msg = new Message();
			if (Integer.valueOf(Constant.pager) <= pager) {
				msg.what = 0;
			} else {
				msg.what = 1;
			}
			myhadler.sendMessage(msg);// 向myhandler发送消息
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler myhadler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				// gridview_goods.removeFooterView(showview);
				break;
			case 1:
				mPhotoWallAdapter.notifyDataSetChanged();
				progress.dismiss();
				// Toast.makeText(getActivity(), "第" + (pager + 1) + "页", 1000)
				// .show();
				break;
			}

		}
	};

	// 点击item时的触发事件
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String detailID = listData.get(arg2).get("photoWall_id");// 获取当前item的id
				Intent intent = new Intent();
				intent.setClass(getActivity(), PhotoWallDetail.class);
				intent.putExtra("detailID", detailID);
				startActivity(intent);
			}
		});

	}

}